<?php
namespace Common\Logic;

/**
 * 用户相关逻辑层
 * @modify trainyao 2016-04-21 创建
 */
class UserLogic extends \Common\Controller\BaseController
{

    /**
     * 检查用户是否存在
     * 方法不会抛异常
     * @modify trainyao 2016-04-27 创建
     * @param  string   $mobile    手机号
     * @return Boolean              存在返回用户信息,不存在返回false
     */
    public function checkUserExist($mobile, $areaCode = null) {
        $userloginModel = D('UserLogin');
        $userInfo = $userloginModel->getInfoByMobile($mobile, $areaCode);
        if ($userInfo['isdelete'] == 1) {
            return false;
        }

        return empty($userInfo) ? false : $userInfo;
    }

    /**
     * 用户登录逻辑
     * 方法会抛异常
     * @modify trainyao 2016-04-21 创建
     * @param  string   $mobile    手机号
     * @param  string   $password  用户密码
     * @return mixin               成功返回用户信息,失败返回false
     */
    public function login($mobile, $password = null, $areaCode = null) {
        $userInfo = $this->checkUserExist($mobile, $areaCode);
        if (empty($userInfo)) {
            throw new \Exception('403,300', 300);
        }

        // 校验密码
        if (!is_null($password)) {
            $password = hash('sha256', $password);
            if ($password != $userInfo['password']) {
                throw new \Exception('403,302', 302);
            }
        }

        return $userInfo;
    }

    /**
     * 用户注册逻辑
     * 方法会抛异常
     * @modify trainyao 2016-04-27 创建
     * @modify wenhui 2017-05-25 新增区号
     * @param  string   $mobile    用户手机号
     * @param  string   $password  用户密码
     * @param  string   $name      姓名
     * @param  string   $areaCode  区号
     * @return boolean              注册执行结果
     */
    public function register($mobile, $password, $name = '', $areaCode = '86') {
        $userInfo = $this->checkUserExist($mobile, $areaCode);
        if (!empty($userInfo)) {
            throw new \Exception('403,301', 301);
            return false;
        }

        $password = hash('sha256', $password);
        $userloginModel = D('UserLogin');
        $registerResult = $userloginModel->register($mobile, $password, $name, $areaCode);
        if (empty($registerResult)) {
            throw new \Exception('500,502', 502);
            return false;
        }

        return true;
    }

    /**
     * 自动用户注册逻辑
     * @modify wenhui 2017-02-15 创建
     * @param  string   $mobile    用户手机号
     * @return boolean              注册执行结果
     */
    public function autoRegister($users, $hotel) {
        // 把入住人进行注册
        $userloginModel = D('UserLogin');
        $userloginModel->startTrans();

        $commit = false;
        foreach ($users as $key => &$usersItem) {
            // 检查是否已注册
            $userInfo = $this->checkUserExist($usersItem['mobile'], $usersItem['areaCode']);
            if (empty($userInfo)) {
                // 没注册
                $string = chr(mt_rand(97,122));
                $truePassword = $string . getRandomNumber(5);
                $password = hash('sha256', $truePassword);
                $registerResult = $userloginModel->register($usersItem['mobile'], $password, $usersItem['name'], $usersItem['areaCode']);
                if ($registerResult) {
                    $commit = true;
                    $usersItem['truePassword'] = $truePassword;
                } else {
                    $commit = false;
                    break;
                }
            }
        }
        unset($usersItem);

        if ($commit) {
            $userloginModel->commit();
            // 注册成功 并发短信
            $loginLink = "http://" . MEIZHU_BOOK_HOST . "/Home/BookPage/index?hotel={$hotel}";
            $loginLink = shortenUrl($loginLink);
            foreach ($users as $key => $userItem) {
                if (isset($userItem['truePassword'])) {
                    if ($userItem['areaCode'] == '86') {
                        $smsUtil = new \Org\Util\Sms();
                        $smsSendResult = $smsUtil->sendNotRegBook($userItem['mobile'], $userItem['truePassword'], $loginLink);
                    } else {
                        $smsUtil = new \Org\Util\yunPian();
                        $smsSendResult = $smsUtil->yunPianSendNotRegBook($userItem['areaCode'], $userItem['mobile'], $userItem['truePassword'], $loginLink);
                    }
                    if (empty($smsSendResult)) {
                        // 发送失败 逻辑处理
                    }
                    // 把账号同步到钥匙包
                    $this->qrclientRegister($userItem['mobile'], $userItem['name'], $userItem['areaCode']);
                }
            }
            unset($userItem);
            return true;
        }  else {
            //事务提交回滚
            $userloginModel->rollback();
            return false;
        }
    }
    
    /**
     * 修改密码
     * 方法会抛异常
     * @modify trainyao 2016-04-27 创建
     * @param  string   $mobile    手机号
     * @param  string   $password  要修改的密码
     * @return mixin              执行失败抛异常
     */
    public function savePassword($mobile, $password, $areaCode = '86') {
        $userInfo = $this->checkUserExist($mobile, $areaCode);
        if (empty($userInfo)) {
            throw new \Exception('403,300', 300);
            return;
        }

        // 执行修改
        $userloginModel = D('UserLogin');
        $password = hash('sha256', $password);
        $saveResult = $userloginModel->savePassword($userInfo['id'], $password);
        if (empty($saveResult)) {
            throw new \Exception('500,503', 503);
            return;
        }
    }

    /**
     * 绑定美住预定用户到第三方登录用户
     * 方法会抛异常
     * @modify trainyao 2016-05-05     创建
     * @param  integer   $userId        美住预定用户id
     * @param  string   $oauthId       第三方平台用户标识
     * @param  integer   $authLoginType 第三方登录渠道
     * @return boolean                  执行结果
     */
    public function bindUser($userId, $oauthId, $authLoginType) {
        // 查询信息是否存在
        $userAuthModel = D('UserAuth');
        $userAuthInfo = $userAuthModel->getInfoByOauthType($oauthId, $authLoginType);
        if (empty($userAuthInfo)) {
            \Org\Util\FileLog::write("$oauthId oauth from $authLoginType data not exist when bind", 1,  'Home/UserAuth');
            throw new \Exception('500,500', 500);
        }

        // 修改用户ID
        $bindResult = $userAuthModel->saveUserId($userAuthInfo['id'], $userId);
        if (empty($bindResult)) {
            throw new \Exception('500,500', 500);
        }

        return true;
    }

    /**
     * rpc 把账号同步到钥匙包
     * @modify wenhui 2017-03-30   创建
     */
    public function qrclientRegister($mobile, $name, $areaCode = '86') {
        // 获取用户id
        $userloginModel = D('UserLogin');
        $webUserData = $userloginModel->getInfoByMobile($mobile, $areaCode);

        // prc调用
        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('QRCLIENTSYNC_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => C('MEIZHU_RPC_FLAG'),
            'time' => time(),
            'mobile' => $mobile,
            'name' => $name,
            'webUserId' => isset($webUserData['id']) ? $webUserData['id'] : null,
            'areaCode' => isset($webUserData['areacode']) ? $webUserData['areacode'] : null,
        );

        $resultData = $client->qrclientRegister($RPCData);
    }

    /**
     * 获取区号时区数据
     * @modify wenhui 2017-06-16
     * @return array $data 时区数据
     */
    public function universalTimeList() {

        Vendor('phpRPC.phprpc_client');
        $client = new \PHPRPC_Client(C('HOTEL_RPC_URL'));
        $client->setEncryptMode(3);
        $RPCData = array(
            'flag' => 'uclbrt',
            'time' => time(),
            'bookLangSet' => LANG_SET,
        );
        $result = $client->bookUniversalTimeList($RPCData);
        return $result;
    }
}
